﻿Imports System.IO
Imports MessageBoxEx
Imports ProgressBarEx
Imports System.Text.RegularExpressions

Public Module modDBMA
    Private _progressCurrentText As String

    Public Enum versionResult

        IsOlder = 1
        IsNewer = 0
        ErrorOne = -1
        ErrorTwo = -2
    End Enum

    Public Structure xmlInformation
        Public idx As Integer
        Public tag As String
        Public value As String
    End Structure

    Public Function Folder_Format(ByVal folder As String) As String

        If Strings.Right(folder, 1) = "\" Then
            Folder_Format = Path.GetDirectoryName(folder)
        Else
            Folder_Format = folder
        End If

    End Function

    Public Function Download_DemonbuddyExe(localPath As String, downloadBar As ProgressBarExtended) As Boolean

        Dim dirDemonbuddy As String = localPath
        Dim dirBackup As String = My.Settings.FolderBackup
        Dim url As New List(Of String)
        Dim _result As en_resultDownload
        Dim tmpZip As en_resultZipExtract

        If Directory_Check(dirDemonbuddy) = False Then GoTo downloadError

        If Directory.GetFiles(dirDemonbuddy).Count > 0 Then

            Dim _Msg =
                    New MsgBoxEx(
                        "This directory is not empty. We must back up this directory before you can continue. Would you like us to backup the folder?",
                        AppDomain.CurrentDomain.FriendlyName)
            _Msg.SetButtons(New String() {"Yes", "No", "Cancel"},
                            New DialogResult() {DialogResult.Yes, DialogResult.No, DialogResult.Cancel}, 2)
            _Msg.ShowDialog(frmMain)

            Dim _msgResult As DialogBoxResult = _Msg.DialogBoxResult

            If _msgResult = DialogBoxResult.Button1 Then

                If Directory.Exists(dirBackup) = False Then Directory.CreateDirectory(dirBackup)

            ElseIf _msgResult = DialogBoxResult.Button3 Then

                GoTo downloadError

            End If

            Backup_Folder(dirDemonbuddy, dirBackup, True, True)

        End If

        url.Add("http://updates.buddyauth.com/GetNewest?filter=DemonbuddyBETA")

        Form_ProgressBar_Update("Downloading DemonbuddyBETA...", 1, 0, 2, downloadBar)

        _result = Download_Start(url, AppDomain.CurrentDomain.BaseDirectory, downloadBar, True)

        If _result = en_resultDownload.dlSuccess Then

            tmpZip = Zip_Extract(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempDemonbuddy.zip"),
                                 dirDemonbuddy)

            If tmpZip = en_resultZipExtract.ziSuccess Then

                Form_ProgressBar_Update("Downloading DemonbuddyBETA... (Complete)", 2, 0, 2, downloadBar)

                File.Delete(Path.Combine(dirDemonbuddy, "tempDemonbuddy.zip"))

            Else

                GoTo downloadError

            End If

            Return True

        End If

downloadError:
        Form_ProgressBar_Update("Error Downloading DemonbuddyBETA...", 0, 0, 2, downloadBar)
        Return False
    End Function

    Public Function Download_PatchExe(localPath As String, downloadBar As ProgressBarExtended) As Boolean

        Dim url As New List(Of String)
        Dim urlResult As en_resultDownload
        Dim dirUtilities As String = localPath

        If Directory_Check(dirUtilities) = False Then GoTo downloadError

        Form_ProgressBar_Update("Downloading Patch Tools...", 0, 0, 2, downloadBar)

        If Directory.GetFiles(dirUtilities).Count > 0 Then

            Dim _MsgPatch =
                    New MsgBoxEx(
                        "This directory is not empty. Would you like to delete the existing files in the directory?",
                        frmMain.Text)
            _MsgPatch.SetButtons(New String() {"Yes", "No"}, New DialogResult() {DialogResult.Yes, DialogResult.No}, 2)
            _MsgPatch.ShowDialog(frmMain)

            Dim _MsgPatchResult As DialogBoxResult = _MsgPatch.DialogBoxResult

            If _MsgPatchResult = DialogBoxResult.Button2 Then Return False

            Directory.Delete(dirUtilities, True)

            Directory.CreateDirectory(dirUtilities)

            GoTo downloadError

        End If

        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/patch.exe")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/cmp.exe")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/diff.exe")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/diff3.exe")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/libiconv2.dll")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/libintl3.dll")
        url.Add("https://github.com/msysgit/msysgit/raw/master/bin/msys-1.0.dll")

        urlResult = Download_Start(url, dirUtilities, downloadBar)

        If urlResult = en_resultDownload.dlSuccess Then

            downloadBar.Value = downloadBar.Maximum
            Form_ProgressBar_Update("Downloading Patch Tools... (Complete)", , , , downloadBar)
            Return True

        End If

downloadError:
        Form_ProgressBar_Update("Error Downloading Patch Tools...", , , , downloadBar)
        Return False
    End Function

    Public Sub Version_Check(sourceObject As Object)

        Dim _textbox As TextBox = CType(sourceObject, TextBox)
        Dim _text As String = _textbox.Text
        Dim _regex As Match = Regex.Match(_text, "(\d+).*?(\d+).*?(\d+)", RegexOptions.IgnoreCase)
        Dim _output As String = Nothing

        If (_regex.Success) Then

            If String_IsEmpty(_regex.Groups(1).Value) = False Then
                _output = _regex.Groups(1).Value
            End If

            If String_IsEmpty(_regex.Groups(2).Value) = False Then
                _output = _output & "." & _regex.Groups(2).Value
            End If

            If String_IsEmpty(_regex.Groups(3).Value) = False Then
                _output = _output & "." & _regex.Groups(3).Value
            End If

            If String_IsEmpty(_regex.Groups(4).Value) = False Then
                _output = _output & "." & _regex.Groups(4).Value
            End If

            If String_IsEmpty(_output) Then
                _textbox.Clear()
            Else
                _textbox.Text = _output
            End If

        End If
    End Sub

    Public Function Version_Compare(verInput As String, verCompare As String) As versionResult

        Dim _one As String = verInput
        Dim _two As String = verCompare

        Dim verOne As Version
        Dim verTwo As Version

        Try

            verOne = Version.Parse(_one)

        Catch ex As Exception

            Return versionResult.ErrorOne

        End Try

        Try

            verTwo = Version.Parse(_two)

        Catch ex As Exception

            Return versionResult.ErrorTwo

        End Try

        If verOne < verTwo Then
            Return versionResult.IsNewer
        Else
            Return versionResult.IsOlder
        End If
    End Function

    Public Function URI_IsValid(ByVal uriAddress As String) As Boolean

        If Not Regex.IsMatch(uriAddress,
                             "^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?") _
            Then
            Return False
        Else
            Return True
        End If
    End Function

    Public Function Menu_CreateSubMenu(ByVal submenuName As String, ByVal submenuTag As String,
                                       ByVal submenuTooltipText As String,
                                       Optional ByVal submenuEnabled As Boolean = True) As ToolStripMenuItem

        Dim mnuItem As ToolStripMenuItem

        mnuItem = New ToolStripMenuItem()

        mnuItem.Text = submenuName
        mnuItem.Tag = submenuTag
        mnuItem.ToolTipText = submenuTooltipText
        mnuItem.Enabled = submenuEnabled

        Return mnuItem
    End Function

    Public Function Form_isOpen(ByVal objectForm As Form) As Boolean

        If Application.OpenForms.OfType(Of Form).Contains(objectForm) Then

            Return True

        Else

            Return False

        End If
    End Function

    Public Sub Form_ListView_AutoResize(ByRef controlListView As ListView)

        Dim _column As ColumnHeader

        controlListView.BeginUpdate()

        For Each _column In controlListView.Columns

            _column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

            Dim widthColumn As Integer = _column.Width

            _column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)

            Dim widthHeader As Integer = _column.Width

            If (widthColumn > widthHeader) Then

                _column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

            End If

            If controlListView Is frmMain.listviewPatchList Then

                If (_column.Index = 2) Or
                   (_column.Index = 3) Or
                   (_column.Index = 4) Or
                   (_column.Index = 5) Or
                   (_column.Index = 6) Then

                    _column.Width = 0

                End If

            End If

            If (_column.Index = (controlListView.Columns.Count - 1)) Then

                _column.Width = -2

            End If

        Next

        controlListView.EndUpdate()
    End Sub

    Public Sub Form_ProgressBar_Update(Optional ByVal statusText As String = Nothing,
                                       Optional ByVal statusValue As Integer = -1,
                                       Optional ByVal statusMin As Integer = -1,
                                       Optional ByVal statusMax As Integer = -1,
                                       Optional ByVal statusObject As Object = Nothing)

        Dim _progressObject As Object = statusObject
        'Dim _progressRedraw As Boolean

        If (_progressObject Is Nothing) Then
            _progressObject = frmMain.progressbarextendedStatus
            _progressObject.AutoUpdatePercentage = False
        End If

        If Not (statusMin = -1) Then
            _progressObject.Minimum = statusMin
        End If

        If Not (statusMax = -1) Then
            _progressObject.Maximum = statusMax
        End If

        If Not (statusValue = -1) Then
            _progressObject.Value = statusValue
        End If

        If Not (statusText Is Nothing) Then

            _progressCurrentText = statusText

        End If

        _progressObject.ShowText(_progressCurrentText)
    End Sub
End Module